<?php

namespace frontend\modules\address\controllers;

use common\models\Wxuser;
use frontend\modules\address\models\EcsRegion;
use frontend\modules\base\controllers\BaseController;
use Yii;
use frontend\modules\address\models\UserAddress;
use frontend\modules\address\models\search\UserAddressSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 用户选中默认地址，查询地址列表，
 *
 * Class UseraddressController
 * @package frontend\modules\address\controllers
 */
class UseraddressController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 获取用户地址列表
     *
     * @desc 获取user_address表属性信息包括（收货人姓名，电话，地址，详细地址，最佳送货时间等）
     * @param string $userid |用户ID|yes|40位|
     *
     * @return array data[] 用户地址列表数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionIndex()
    {
        $userid = Yii::$app->UserInfo->userid;

        $userAddress = UserAddress::find()->where(['user_id'=>$userid])->asArray()->all();
        $addressId = Wxuser::findOne(['id'=>$userid])->address_id;

        foreach($userAddress as $k=>$v) {
            $ex = new \frontend\modules\address\lib\AddExchange();
            $userAddress[$k] = $ex->exchangeArr($v);
            if($v['address_id']==$addressId) {
                $userAddress[$k]['is_def'] = 1;
            }else{
                $userAddress[$k]['is_def'] = 0;
            }
        }

        $message = ['code'=>200,'message'=>'用户地址数据获取成功','data'=>$userAddress];
        return json_encode($message);
    }

    /**
     * 获取地址列表，多级数组
     *
     *
     * @return array data[] 地址列表多级数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionRegionlist()
    {
        $regin =new EcsRegion();
        $jsonAll = $regin->getJsonAll();
        $message = ['code'=>200,'message'=>'登录成功','data'=>$jsonAll];
        return json_encode($message);
    }

    /**
     * 用户创建个人地址，设置是否默认
     *
     * @desc 新增地址
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string data[is_def] |是否默认地址|yes|
     * @param string data[tel] |用户电话号码|yes|
     * @param string data[email] |收货人邮件|yes|
     * @param string data[consignee] |收货人名称|yes|
     * @param string data[country] |国家region_id|no|
     * @param string data[province] |省份region_id|yes|
     * @param string data[city] |市区region_id|yes|
     * @param string data[district] |地区region_id|yes|
     * @param string data[address] |详细地址|yes|
     *
     * @return array data[] 地址列表多级数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionSetuseradd()
    {
        $this->setPost();
        $postData = $this->post['data'];
        $userid = \Yii::$app->UserInfo->userid;
        if(!$userid) {
            echo  'session 过期';exit;
        }

        $beginTransaction = Yii::$app->db->beginTransaction();
        try{
            $userAddress = new UserAddress();
            $userAddress->country = 1;
            $userAddress->province = $postData['province'];
            $userAddress->city = $postData['city'];
            $userAddress->district = $postData['district'];
            $userAddress->consignee = $postData['consignee'];
            $userAddress->email = $postData['email'];
            $userAddress->tel = $postData['tel'];
            $userAddress->address = $postData['address'];
            $userAddress->user_id = $userid;
            if($userAddress->save())  {
                if($postData['is_def']==1) {
                    $wxUser = Wxuser::findOne($userid);
                    $wxUser->address_id = $userAddress->address_id;
                    if(!$wxUser->save()) {
                        throw new Exception('用户地址保存失败！');
                    }
                }
                $message = ['code'=>200,'message'=>'用户地址数据保存成功','data'=>$userAddress];
                $beginTransaction->commit();
                return json_encode($message);
            }
            throw new Exception('用户地址保存失败！');
        }catch (Exception $e){
            $beginTransaction->rollBack();
            $message = ['code'=>500,'message'=>$e->getMessage()];
            return json_encode($message);
        }
    }

    /**
     * 编辑个人地址，设置是否默认
     *
     * @desc 地址编辑
     *
     * @param string $userid |用户ID|yes|40位|
     * @param int data[address_id] |用户地址ID|yes|
     * @param string data[is_def] |是否默认地址|yes|
     * @param string data[tel] |用户电话号码|yes|
     * @param string data[email] |收货人邮件|yes|
     * @param string data[consignee] |收货人名称|yes|
     * @param string data[country] |国家region_id|yes|
     * @param string data[province] |省份region_id|yes|
     * @param string data[city] |市区region_id|yes|
     * @param string data[district] |地区region_id|yes|
     * @param string data[address] |地区region_id|yes|
     *
     * @return array data[] 地址列表多级数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionSetuseredit()
    {
        $this->setPost();
        $postData = $this->post['data'];
        $userid = \Yii::$app->UserInfo->userid;
        if(!$userid) {
            echo  'session 过期';exit;
        }

        $beginTransaction = Yii::$app->db->beginTransaction();
        try{
            $userAddress = UserAddress::findOne($postData['address_id']);
            if($userAddress){
                $userAddress->country = 1;
                $userAddress->province = $postData['province'];
                $userAddress->city = $postData['city'];
                $userAddress->district = $postData['district'];
                $userAddress->consignee = $postData['consignee'];
                $userAddress->email = $postData['email'];
                $userAddress->tel = $postData['tel'];
                $userAddress->address = $postData['address'];
                $userAddress->user_id = $userid;
                if($userAddress->save())  {
                    $wxUser = Wxuser::findOne($userid);
                    if($postData['is_def']==1) {
                        $wxUser->address_id = $userAddress->address_id;
                        if(!$wxUser->save()) {
                            throw new Exception('用户地址保存失败！');
                        }
                    } elseif($postData['is_def']==0&&$wxUser->address_id>0) {
                        $wxUser->address_id = 0;
                        if(!$wxUser->save()) {
                            throw new Exception('用户地址保存失败！');
                        }
                    }
                    $message = ['code'=>200,'message'=>'用户地址数据保存成功','data'=>$userAddress];
                    $beginTransaction->commit();
                    return json_encode($message);
                }
                throw new Exception('用户地址保存失败！');
            }

        }catch (Exception $e){
            $beginTransaction->rollBack();
            $message = ['code'=>500,'message'=>$e->getMessage()];
            return json_encode($message);
        }
    }

    /**
     * 获取用户默认地址
     *
     * @desc 默认地址
     * @param string $userid |用户ID|yes|40位|
     *
     * @return array data[] 地址列表多级数组
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionDefaddress()
    {
        $this->setPost();
        $userid = \Yii::$app->UserInfo->userid;
        if(!$userid) {
            echo  'session 过期';exit;
        }
        $address_id = Wxuser::findOne($userid)->address_id;
        $userAddress = [];
        if($address_id>0) {
            $userAddress = UserAddress::find()->where(['address_id'=>$address_id])->asArray()->one();
            if(!$userAddress){
                $message = ['code'=>500,'message'=>'没有设置默认地址','data'=>[]];
                return json_encode($message);
            }
            $ex = new \frontend\modules\address\lib\AddExchange();
            $userAddress = $ex->exchangeArr($userAddress);
        }
        $message = ['code'=>200,'message'=>'用户地址获取成功','data'=>$userAddress];
        return json_encode($message);
    }

    /**
     * 删除用户地址
     *
     * @desc 删除用户地址
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param int data[address_id] |用户地址ID|yes|
     *
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     */
    public function actionDeladdress()
    {
        $userinfo = $this->checkAccessToken();
        $post = $this->post;
        $postData = $post['data'];
        if(is_object($userinfo)) {
            if ($userinfo) {
                $address_id = $postData['address_id'];
                $userAddress = UserAddress::findOne($address_id);
                if($userAddress&&$userAddress->delete()) {
                    $message = ['code'=>200,'message'=>'用户地址删除成功','data'=>[]];
                    return json_encode($message);
                } else {
                    $message = ['code'=>200,'message'=>'用户地址删除失败','data'=>[]];
                    return json_encode($message);
                }
            }
        }else {
            return $userinfo;
        }

    }

    /**
     * 设置用户默认地址
     *
     * @desc 设置用户默认地址
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param int data[address_id] |用户地址ID|yes|
     * @param int data[is_def] |是否默认|yes|1或0
     *
     * @return string message 提示信息
     * @exception 200 参数传递错误
     * @exception 500 服务器内部错误
     */
    public function actionSetdef()
    {
        $userinfo = $this->checkAccessToken();
        $post = $this->post;
        $postData = $post['data'];
        if(is_object($userinfo)) {
            if ($userinfo) {
                $address_id = $postData['address_id'];
                $is_def = $postData['is_def'];
                if($is_def) {

                } else {
                    $address_id = 0;
                }
                $wxUser = Wxuser::findOne(['id'=>Yii::$app->UserInfo->userid]);
                $wxUser->address_id = $address_id;
                if($wxUser->save()) {
                    $message = ['code'=>200,'message'=>'默认地址设置成功','data'=>[]];
                    return json_encode($message);
                }
            }
        }else {
            return $userinfo;
        }
    }
}
